<template>
    <div class="registerView">
        <div class="container">
            <div class="title">注册</div>
            <div class="formBox">
                <form>
                    <div class="inputBox">
                        <span>用户名：</span>
                        <input type="text" name="username" v-model="form.username" placeholder="请输入用户名" />
                    </div>
                    <div class="inputBox noPadding">
                        <span>头像：</span>
                        <div class="avatarBox">
                            <!-- 头像预览 -->
                            <div class="avatar">
                                <img :src="form.avatar" alt="" />
                            </div>
                            <!-- 选择文件 -->
                            <div class="upload" @click="openImageProcessingDialog">
                                <span class="iconfont icon-likesprogramshangchuan"></span>
                                <span class="uploadText">上传图片</span>
                            </div>
                        </div>
                    </div>
                    <div class="inputBox">
                        <span>密码：</span>
                        <input type="password" name="password" v-model="form.password" placeholder="请输入密码" />
                    </div>
                    <div class="inputBox">
                        <span>确认密码：</span>
                        <input type="password" name="confirmPassword" v-model="form.confirmPassword" placeholder="请确认密码" />
                    </div>
                    <div class="inputBox">
                        <span>手机号：</span>
                        <input type="tel" name="phoneNumber" v-model="form.phoneNumber" placeholder="请输入手机号" />
                    </div>
                    <div class="inputBox">
                        <span>验证码：</span>
                        <input type="text" name="phoneCode" v-model="form.phoneCode" placeholder="请输入验证码" />
                        <div 
                            class="getPhoneCode" 
                            :class="{ 'counting': isCounting }"
                            @click="!isCounting && openImageCodeDialog()"
                        >
                            {{ countdownText }}
                        </div>

                    </div>
                    <div class="message" v-if="form.message">{{ form.message }}</div>
                    
                    <div class="inputBox">
                        <div class="btn" @click="register">注册</div>
                    </div>
                    
                    <!-- 协议 -->
                    <div class="protocol">
                        <label class="checkbox">
                            <input type="checkbox" v-model="form.option.protocol" />
                            <span>
                                已同意
                                <router-link to="/user/agreement">《本平台用户协议》</router-link>
                                和
                                <router-link to="/user/agreement">《本平台隐私政策》</router-link>
                            </span>
                        </label>
                    </div>
                </form>
            </div>
        </div>

        <!-- 图片编辑对话框 -->
        <ImageProcessingDialog ref="imageProcessingDialog"
            :previeRadius="'50%'"
            @returnImage="returnImage"
        />

        <!-- 获取验证码对话框，验证图片验证码 -->
         <MessageDialog ref="imageCodeDialog">
            <template v-slot:title>
                <span>验证码</span>
            </template>
            <template v-slot:content>
                <div class="imageCodeBox">
                    <div class="message" v-if="form.verifyCode.message">{{ form.verifyCode.message }}</div>
                    <div class="imageCode">
                        <div class="imageCodeText">请输入验证码</div>
                        <img :src="form.verifyCode.code"  @click="ChangeCheckCode"></img>
                    </div>
                    <div class="imageCodeEditor">
                        <input type="text" v-model="form.verifyCode.checkCode" placeholder="请输入验证码" />
                    </div>
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="imageCodeDialog.Close">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton" @click="getPhoneCode">
                    <span>确认</span>
                </div>
            </template>
         </MessageDialog>
         

        <!-- 获取验证码对话框，验证图片验证码 -->
        <MessageDialog ref="messageCodeDialog">
            <template v-slot:title>
                <span>发送成功</span>
            </template>
            <template v-slot:content>
                <div class="imageCodeBoxMessage">
                    验证码已发送至您的手机。
                </div>
            </template>
            <template v-slot:footer>
                <div class="dialogFooterButton" @click="messageCodeDialog.Close">
                    <span class="line">取消</span>
                </div>
                <div class="dialogFooterButton"  @click="startCountdown">
                    <span>确认</span>
                </div>
            </template>
         </MessageDialog>
    </div>
</template>

<script lang="ts">
import { onBeforeUnmount, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import MessageDialog from '@/components/MessageDialog.vue';
import { userAvatar } from  '@/types/Base64Image';
import { codeApi, userApi } from '@/api/Users';

export default {
    name: 'registerView',
}
</script>

<script setup lang="ts">
    const router = useRouter();
    const form = reactive({
        username: '',
        avatar: userAvatar(),  // 用户头像
        password: '',
        confirmPassword: '',
        verifyCode: {  // 验证码图片
            checkCode: '',
            message: '',
            code: '',
            sessionId: ''
        },
        phoneNumber: '',
        phoneCode: '',// 手机验证码
        message: '',
        option: {
            protocol: false
        }
    });

    // 图片编辑框
    const imageProcessingDialog = ref();
    // 打开图片编辑框
    const openImageProcessingDialog = () => {
        imageProcessingDialog.value.Show();
    };
    // 返回图片
    const returnImage = (image) => {
        form.avatar = image;
    };

    // 打开获取验证码对话框
    const imageCodeDialog = ref();
    const messageCodeDialog = ref();
    const openImageCodeDialog = () => {
        if (isCounting.value) return; // 如果正在倒计时，则不执行
        form.message = ""
        form.verifyCode.message = ""
        if (!form.phoneNumber) {
            form.message = '请填写手机号！';
            return;
        }
        ChangeCheckCode();
        imageCodeDialog.value.Show();
        
    };
    
    // 图片验证码点击事件
    const ChangeCheckCode = () => {
        form.phoneCode = '';
        codeApi.getImageCode().then(res => {
            form.verifyCode.checkCode = '';
            form.verifyCode.code = res.data.code;
            form.verifyCode.sessionId = res.data.sessionId;
        });
    }

    // 获取短信验证码
    const getPhoneCode = async () => {
        form.verifyCode.message = ""
        if (!form.phoneNumber || !form.verifyCode.checkCode) {
            form.verifyCode.message = '请填写验证码！';
            return;
        }
        codeApi.getSmsCode({
            phoneNumber: form.phoneNumber,
            imageCode: {
                code: form.verifyCode.checkCode,
                sessionId: form.verifyCode.sessionId
            }
        }).then(res => {
            form.verifyCode.message = res.message;
            if (res.code === 200)
            {
                imageCodeDialog.value.Close();
                messageCodeDialog.value.Show();
                
            }
            else ChangeCheckCode();
        });
    };

    // 倒计时配置
    const COUNTDOWN_DURATION = 60; // 可调整的倒计时时长
    // 倒计时相关状态
    const countdown = ref(0); 
    const isCounting = ref(false);
    const countdownText = ref('获取验证码');
    let countdownTimer = null;

    // 开始倒计时
    const startCountdown = () => {
        messageCodeDialog.value.Close();
        isCounting.value = true;
        countdown.value = COUNTDOWN_DURATION;
        updateCountdownText();

        countdownTimer = setInterval(() => {
            countdown.value--;
            updateCountdownText();

            if (countdown.value <= 0) {
                clearInterval(countdownTimer);
                isCounting.value = false;
                countdownText.value = '获取验证码';
            }
        }, 1000);
    };

    // 更新倒计时文本
    const updateCountdownText = () => {
        countdownText.value = `${countdown.value}秒后重新获取`;
    };

    // 在组件卸载时清除定时器
    onBeforeUnmount(() => {
        if (countdownTimer) {
            clearInterval(countdownTimer);
        }
    });
    const register = async () => {
        form.message = '';
        if (!form.option.protocol) {
            form.message = '请先同意协议';
            return;
        }
        // 表单验证
        if (!form.username || !form.password || !form.confirmPassword || !form.phoneCode || !form.phoneNumber) {
            form.message = '请填写完整信息';
            return;
        }

        if (form.password !== form.confirmPassword) {
            form.message = '两次密码不一致';
            return;
        }

        try {
            // 调用注册接口
            const response = await userApi.register({
                username: form.username,
                password: form.password,
                phoneNumber: form.phoneNumber,
                avatar: form.avatar,
                phoneCode: form.phoneCode,
        });

        // 根据响应结果处理
        if (response.code === 200) {
            // 注册成功
            form.message = '注册成功！';
            
            // 可以跳转到登录页或其他页面
            router.push({ name: 'login' });
            
            // 或者显示成功提示
            // successDialog.value.Show();
        } else {
            // 注册失败，显示后端返回的错误信息
            form.message = response.message || '注册失败，请稍后重试';
        }

        } catch (error) {
            console.error('Register error:', error);
            form.message = '注册失败，请稍后重试';
        }
    };
</script>

<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
.registerView {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.registerView .container {
    height: 100%;
}

.registerView .container .title {
    width: 100%;
    height: 28px;
    font-size: 20px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
}


/* 表单 */
.registerView .container .formBox {
    width: 100%;
    height: calc(100% - 35px);
    display: flex;
    justify-content: center;
    align-items: center;
}
.registerView .container form {
    width: 400px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}

/* 宽度 */
.registerView .container form .inputBox,
.registerView .container form .message,
.registerView .container form .option,
.registerView .container form .protocol {
    width: 350px;
}

/* 输入框盒子 */
.registerView .container form .inputBox {
    padding: 10px 0px;
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.registerView .container form .inputBox.noPadding {
    padding: 5px 0px;
}

/* 错误信息 */
.registerView .container form .message {
    margin-top: 5px;
    font-size: 14px;
    color: rgba(255, 0, 0, 1);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 链接 */
.registerView .container form a {
    color: rgba(65, 185, 255, 1);
    transition: .3s all;
}
.registerView .container form a:hover {
    color: rgb(0, 162, 255);
}
.registerView .container form a:active {
    color: rgba(65, 185, 255, 1);
    transition: .1s all;
    font-weight: lighter;
}

/* 输入框 */
.registerView .container form .inputBox span {
    min-width: 85px;
}
.registerView .container form .inputBox input {
    width: 100%;
    height: 35px;
    font-size: 16px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
}
.registerView .container form .inputBox input:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

/* 头像盒子 */
.registerView .container form .inputBox .avatarBox {
    width: 100%;
    height: 45px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
/* 头像预览 */
.registerView .container form .inputBox .avatarBox .avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    border: 2px solid rgba(200, 200, 200, 1);
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 16px;
    cursor: pointer;
    transition: .3s all;
}
.registerView .container form .inputBox .avatarBox .avatar img {
    width: 100%;
    height: 100%;
}
/* 上传按钮 */
.registerView .container form .inputBox .avatarBox .upload {
    width: 42px;
    height: 42px;
    margin-left: 20px;
    border-radius: 5px;
    border: 2px solid rgba(200, 200, 200, 1);
    color: rgba(100, 100, 100, 1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    transition: .3s all;
}
.registerView .container form .inputBox .avatarBox .upload .iconfont {
    min-width: 0px;
    min-height: 0px;
    font-size: 24px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.registerView .container form .inputBox .avatarBox .upload .uploadText {
    height: 12px;
    min-width: 0px;
    min-height: 0px;
    font-size: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.registerView .container form .inputBox .avatarBox div:hover {
    border: 2px solid rgba(65, 185, 255, 1);
    color: rgba(65, 185, 255, 1);
}
.registerView .container form .inputBox .avatarBox div:active {
    border: 2px solid rgba(65, 185, 255, .7);
    color: rgba(65, 185, 255, .7);
    transition: .1s all;
}

/* 获取验证码按钮 */
.registerView .container form .inputBox .getPhoneCode {
    min-width: 100px;
    height: 35px;
    background-color: rgba(65, 185, 255, 1);
    border-radius: 5px;
    margin-left: 10px;
    color: white;
    font-size: 12px;
    transition: .3s all;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
/* .registerView .container form .inputBox .getPhoneCode:hover {
    background-color: rgb(0, 162, 255);
}
.registerView .container form .inputBox .getPhoneCode:active {
    transition: .1s all;
    background-color: rgba(65, 185, 255, 1);
} */

/* 倒计时状态样式 */
.registerView .container form .inputBox .getPhoneCode.counting {
    background-color: #c0c4cc;
    cursor: not-allowed;
}
/* 交互状态 */
.registerView .container form .inputBox .getPhoneCode:not(.counting):hover {
    background-color: #66b1ff;
}

.registerView .container form .inputBox .getPhoneCode:not(.counting):active {
    background-color: #3a8ee6;
}


/* 图片验证码对话框 */
.imageCodeBox {
    padding: 0px 20px;
}
.imageCodeBox .message {
    font-size: 14px;
    color: rgba(255, 0, 0, 1);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.imageCodeBoxMessage {
    font-size: 18px;
    color: rgb(12, 141, 0);
    padding: 0px 20px;
}
.imageCodeBox .imageCode {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}
.imageCodeBox .imageCode img {
    min-width: 100px;
    height: 35px;
    overflow: hidden;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    margin-left: 10px;
    transition: .3s all;
    display: flex;
    justify-content: center;
    align-items: center;
}
.imageCodeBox .imageCode img:hover {
    border: 2px solid rgba(65, 185, 255, 1);
}
.imageCodeBox .imageCodeEditor input {
    width: 100%;
    height: 35px;
    font-size: 16px;
    border: 2px solid rgba(200, 200, 200, 1);
    border-radius: 5px;
    padding: 0px 10px;
    outline: none;
}
.imageCodeBox .imageCodeEditor input:focus {
    border: 2px solid rgba(65, 185, 255, 1);
}

/* 注册按钮 */
.registerView .container form .btn {
    width: 100%;
    height: 40px;
    background-color: rgba(65, 185, 255, 1);
    border-radius: 5px;
    color: white;
    font-size: 16px;
    transition: .3s all;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.registerView .container form .btn:hover {
    font-size: 18px;
    background-color: rgb(0, 162, 255);
}
.registerView .container form .btn:active {
    font-size: 16px;
    transition: .1s all;
    background-color: rgba(65, 185, 255, 1);
}

/* 同意协议选择框 */
.registerView .container form .protocol {
    height: 35px;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 复选框 */
.registerView .container form .checkbox {
    padding-left: 3px;
    width: 100%;
    height: 35px;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.registerView .container form .checkbox input {
    width: 12px;
    height: 12px;
}
.registerView .container form .checkbox input:before {
  content: "";
  display: inline-block;
  width: 100%;
  height: 100%;
  font-size: 12px;
  font-weight: bold;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 1);
  outline: 3px solid rgba(180, 180, 180, 1);
}
.registerView .container form .checkbox input:checked:before {
  content: "\2713";
  color: rgba(65, 185, 255, 1);
  outline: 3px solid rgba(65, 185, 255, 1);
}
.registerView .container form .checkbox span {
    padding-left: 10px;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 对话框底部按钮 */
.dialogFooterButton {
    width: 100%;
    height: 65px;
    position: relative;
    display: flex;
    color: rgba(65, 185, 255, 1);
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: .3s all;
}
.dialogFooterButton:hover {
    background-color: rgba(200, 200, 200, .15);
}
.dialogFooterButton:active {
    transition: .1s all;
    background-color: rgba(220, 220, 220, .1);
}
.dialogFooterButton .line {
    width: 100%;
    border-right: 1px solid rgba(200, 200, 200, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>